package com.scalar.chiptrack.adaptor.ikanos;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.utils.ParserResult;
import com.scalar.chiptrack.adaptor.utils.Parser;
import com.scalar.chiptrack.adaptor.utils.ParserFactory;
import com.scalar.chiptrack.adaptor.utils.XLSParserImpl;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.db.DataSource;
import com.scalar.ScalarException;

import java.io.File;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: munugoti
 * Date: 13 Jul, 2010
 * Time: 5:43:18 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProductParser extends JobHandler implements AdaptorConstants
{
    private Logger m_parserLogger       = null;
    private String m_dataOutputDir      = null;

    public  ProductParser() throws ScalarException
    {
        try
        {
            m_dataOutputDir = ConfigManager.getProductPortingFileDir();

            if ( m_dataOutputDir != null )
            {
                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );

                m_parserLogger= AdaptorUtils.getDataParserLogger( m_dataOutputDir,"PRODUCT" );

                AdaptorUtils.setLogger( m_parserLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading PRODUCT output directory details from database, Exception: " + se );
            System.out.println( "ERROR!! ERROR!! ERROR!! Exception while loading PRODUCT output directory details from database, Exception: " + se );
        }
    }
    public static void main( String args[] ) throws Exception
    {
        try
        {
            new ProductParser().execute();
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    public void execute() throws Exception
    {
        AdaptorUtils.printHeader( "PRODUCT", CONSTANT_PARSER );

        File doneDestDir = new File( m_dataOutputDir + "/done" );
        File dataoutDir  = new File( m_dataOutputDir );

        File[] fileList = dataoutDir.listFiles();

        if ( ( fileList == null ) || (fileList.length <= 3))
        {
            log("No file found in directory: " + dataoutDir);
            System.out.println("No file found in directory: " + dataoutDir );
            throw new ScalarException("No file found in directory: " + dataoutDir+ "----\n\n" );
        }

        ArrayList<File> successFileList = new ArrayList<File>();

        boolean success = false;

        for ( int i = 0; i < fileList.length; i++ )
        {
            if ( fileList[i].isDirectory() )
            {
                continue;
            }

            try
            {
                if ( fileList[i].getName().startsWith( ProductAdaptor.FILE_NAME )  || fileList[i].getName().indexOf( ProductAdaptor.FILE_NAME )  != -1)
                {
                     parseProductReport( fileList[i].getAbsolutePath() );
                                          
                     successFileList.add(fileList[i]);
                }

                success = true;
            }
            catch (Exception e)
            {
                success = false;
                log("Exception while parsing file: " + fileList[i].getAbsolutePath() + "\nException: " + e);
                e.printStackTrace();
                throw e;
            }
        }

        int adaptor_id = AdaptorRunInfo.getLastRunAdaptorId( ProductAdaptor.ADAPTOR_NAME, CONSTANT_ADAPTOR);
        // transaction 9
        try
        {
            if (success)
            {
                AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, ProductAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
                System.out.println("SUCCESSFULLY UPDATED IN THE DATABASE");
            }
        }
        catch (ScalarException se)
        {
            success = false;  //As filES DATA SAVED , UPDATEING AS SUCCESS
            AdaptorRunInfo.saveAdaptorLastUpdatedStatus(CONSTANT_PARSER, ProductAdaptor.ADAPTOR_NAME, CONSTANT_SUCCESS, adaptor_id);
            log("WARNING!! WARNING!! WARNING!! Could not update Adaptor run information, Exception: " + se);
            throw se;
        }

        // Step 10
        // Move the successful files to 'done' directory
        if (success)
        {
            System.out.println("successFileList = " + successFileList.size() );
            System.out.println("doneDestDir = " + doneDestDir);
            AdaptorUtils.moveFilesToDone( successFileList, doneDestDir);
        }
    }

    private void parseProductReport (String fileName ) throws Exception
    {
        if ( fileName == null ) throw new ScalarException( "Filename argument is null" );

        ParserResult result = null;
        
        Connection conn         = null;
		PreparedStatement pstmt = null;
        boolean success = false;

        conn = DataSource.getConnection();
        try
        {
            File productMasterFile = new File( fileName );
            if ( !productMasterFile.exists() )
            {
                throw new ScalarException( fileName + " doesnt exist" );
            }

            Parser parser = ParserFactory.getXLSParser( productMasterFile );
            log( "\nFound " + fileName );
            log( "\nParsing the file for Wip Report..." );
            System.out.println( "\nFound " + fileName );
            System.out.println( "\nParsing the file for Product details Report..." );
            
            ((XLSParserImpl)parser).setHeaderRowIdx(2);
            ((XLSParserImpl)parser).setDataStartRowIdx(3);

            pstmt = conn.prepareStatement( " { CALL SP_CREATE_UPDATE_PRODUCT_INFO_BY_FG_PART (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " +
                    "   ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) }" );
            result = parser.parse();

            String qtrStr = ((String)result.getHeadings().get(30) ).substring(0,5);
            
            while ( result.next() )
            {

                if ( result.getString("Manufacturing Part Number") != null && result.getString("Manufacturing Part Number").trim().length() > 0 )
                {
                    pstmt.setString( 1, result.getString ( "Fab Part" ) );
                    pstmt.setString( 2, result.getString ( "Manufacturing Part Number" ) );
                    pstmt.setString( 3, result.getString ( "Marketing Part Number" ) );
                    pstmt.setString( 4, result.getString ( "Planner Code" ) );
                    pstmt.setInt( 5, result.getInt ( "Dies/Package" ) );
                    pstmt.setString( 6, result.getString ( "MCM Part" ) );
                    pstmt.setInt( 7, result.getInt ( "MCM Qty" ) );
                    pstmt.setString( 8, result.getString ( "Part Status" ) );
                    pstmt.setString( 9, result.getString ( "Chip Family" ) );
                    pstmt.setInt( 10, result.getInt ( "Port" ) );
                    pstmt.setString( 11, result.getString ( "Chip Set" ) );
                    pstmt.setString( 12, result.getString ( "Wafer Sort Vendor1" ) );
                    pstmt.setString( 13, result.getString ( "Wafer Sort Vendor2" ) );

                    pstmt.setString( 14, result.getString ( "Package" ) );
                    pstmt.setString( 15, result.getString ( "Package Size" ) );
                    pstmt.setInt( 16, result.getInt ( "Pin Count" ) );
                    pstmt.setString( 17, result.getString ( "Wire to Package Ball ratio" ) );
                    pstmt.setString( 18, result.getString ( "Substrate Technology" ) );
                    pstmt.setString( 19, result.getString ( "Substrate Layer" ) );
                    pstmt.setString( 20, result.getString ( "Assembly Vendor1" ) );
                    pstmt.setString( 21, result.getString ( "Assembly Vendor2" ) );
                    pstmt.setString( 22, result.getString ( "Tester Platform" ) );
                    pstmt.setString( 23, result.getString ( "Test Time" ) );
                    pstmt.setString( 24, result.getString ( "Index Time" ) );
                    pstmt.setString( 25, result.getString ( "Vendor Tester Cost/Hr" ) );
                    pstmt.setString( 26, result.getString ( "Consigned Tester/Hr" ) );
                    pstmt.setString( 27, result.getString ( "Test Vendor1" ) );
                    pstmt.setString( 28, result.getString ( "Test Vendor2" ) );
                    pstmt.setString( 29, result.getString ( "FG Vendor1" ) );
                    pstmt.setString( 30, result.getString ( "FG Vendor2" ) );
                                        
                    pstmt.setDouble( 31, result.getDouble ( 30 ) );
                    pstmt.setDouble( 32, result.getDouble ( 31 ) );
                    pstmt.setDouble( 33, result.getDouble ( 32 ) );
                    pstmt.setDouble( 34, result.getDouble ( 33 ) );

                    pstmt.setInt( 35, result.getInt ( 34 ) ); //Plan NDW

                    pstmt.setDouble( 36, result.getDouble(35) * 100  );
                    pstmt.setDouble( 37, result.getDouble ( 36 )* 100 );
                    pstmt.setDouble( 38, result.getDouble ( 37 )* 100 );

                    pstmt.setDouble( 39, result.getDouble ( "Fab Cycle Time" ) );
                    pstmt.setDouble( 40, result.getDouble ( "Sort Cycle Time" ) );
                    pstmt.setDouble( 41, result.getDouble ( "Assembly Cycle Time" ) );
                    pstmt.setDouble( 42, result.getDouble ( "Test Cycle Time" ) );
                    pstmt.setDouble( 43, result.getDouble ( "EOL Cycle Time" ) );
                    
                    pstmt.setInt( 44, result.getInt ( "T/R & Tray Qty" ) );
                    pstmt.setInt( 45, result.getInt ( "Inner Box Qty" ) );
                    pstmt.setInt( 46, result.getInt ( "Carton Qty" ) );
                    pstmt.setDouble( 47, result.getDouble ( "Weight / Box" ) );
                    pstmt.setString( 48, result.getString ( "ECCN" ) );
                    pstmt.setString( 49, result.getString ( "HTS Code" ) );
                    pstmt.setString( 50, result.getString ( "CCATS" ) );
                    pstmt.setString( 51, qtrStr.substring(2,3) );
                    pstmt.setString( 52, "20"+qtrStr.substring(3,5) );

                    pstmt.addBatch();
                }
            }
            //pstmt.executeBatch();
            success = true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw e;
        }
        finally
        {

            try
            {
                if (conn != null)
                {
                    if( success )
                    {
                        conn.commit();
                    }
                    else
                    {
                        conn.rollback();
                    }
                }
            }
            catch (SQLException ignore) {System.out.println("Sql exception ");}

            if ( pstmt != null )
            {
                try { pstmt.close(); } catch (SQLException ignore){}
            }
            if ( conn != null )
            {
                try { conn.close(); } catch (SQLException ignore){}
            }
        }
    }

    private void log( String message )
    {
      if ( message == null ) return;

      if ( m_parserLogger != null )
      {
          m_parserLogger.logDebug( message + LINE_SEPARATOR );
      }
      else
      {
          System.out.println( message );
      }
    } // end of log method
}
